<template>
  <div class="perception_edit">
    <el-input v-model="title" clearable placeholder="请输入文章标题"></el-input>
    <Wangeditor style="margin: 10px 0;" :perception_body="perception.body" :zt=true  @get_html="getevent" ></Wangeditor>
    <el-button @click="edit" style="margin-right: 40px">修改文章</el-button><el-checkbox v-model="overt">公开文章</el-checkbox>
  </div>
</template>

<script>
import Wangeditor from "../../components/Wangeditor"
import qs from "qs";
import {delImgArticle, editArticle} from "../../utils/api";
export default {
  name: "PerceptionEdit",
  mounted() {
    this.perception=this.$route.params.pinfo;
    this.overt=this.perception.overt==0?true:false
    this.title=this.perception.title;
  },
  data(){
    return {
      perception:{},
      body:'',
      title:'',
      imgArray:[],  //原来文章中的图片
      isEdit:false,
      overt:true,
      chirldEditor:null,
      newImg:[]
    }
  },
  components:{
    Wangeditor
  },
  methods:{
    edit(){ //用户修改文章后 找出被删除的图片
      if(this.perception.body!==this.body || this.perception.title!==this.title || this.perception.overt!==(this.overt?0:1)){
        editArticle(qs.stringify({body:this.body,title:this.title,pid:this.perception.id,overt:this.overt?0:1})).then(respose=>{
          if (respose.status===200){
            //查找出被删除的图片
            let deletedArr = [];
            if(this.imgArray?.length>0 || this.newImg?.length>0){
              let newImgArr
              newImgArr = this.chirldEditor.getElemsByType('image')?.map(v=>v?.src)
              if(this.imgArray?.length>0){
                this.imgArray.forEach((item) => {
                  if (newImgArr.filter((v) => v == item).length == 0) {
                    deletedArr.push(item);
                  }
                });
              }
              if(this.newImg?.length>0){
                this.newImg.forEach((item) => {
                  if (newImgArr.filter((v) => v == item).length == 0) {
                    deletedArr.push(item);
                  }
                });
              }
            }
            if(deletedArr?.length>0){
              //有删除图片 只有修改成功 我们才回去操作删除的图片
              delImgArticle(qs.stringify({imgsrc: JSON.stringify(deletedArr)})).then().catch()
              localStorage.removeItem("editaddtupian");
              localStorage.removeItem("editnewdelImg");
            }
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success'
            });
            this.isEdit=true
            this.$router.replace({name:'perceptionlook',query:{id:this.perception.id}})
          }
        }).catch(error=>{
          console.log(error)
        })
      }else{ //用户内容没有改变，无法发起修改请求
        this.$message.warning("你还没有修改呢！")
      }
    },
    getevent(v,editor,allimg,newImg){
      this.body=v;
      this.chirldEditor = editor //editor.getElemsByType('image')?.map(v=>v.src)
      this.imgArray=allimg;

      // //每次改变时 获取新增的图片
      // let newImgArr = this.chirldEditor.getElemsByType('image')?.map(v=>v?.src)
      // let addedArr = [];
      // newImgArr.forEach((item) => {
      //   if (this.imgArray.filter((v) => v == item).length == 0) {
      //     addedArr.push(item);
      //   }
      // });
      // localStorage.setItem('editaddtupian',addedArr)

      //检查新插入的图片中有无被删除的
      if(newImg.length>0){
        this.newImg = newImg
        let deletedArr = [];
        let newImgArr = this.chirldEditor.getElemsByType('image')?.map(v=>v?.src)
        newImg.forEach((item) => {
          if (newImgArr.filter((v) => v == item).length == 0) {
            deletedArr.push(item);
          }
        });
        localStorage.setItem('editnewdelImg',deletedArr)
      }
    },
    getNewArr(a, b) {
      const arr = [...a, ...b];
      const newArr = arr.filter(item => {
        return !(a.includes(item) && b.includes(item));
      });
      return newArr;
    },
  },
  beforeRouteLeave(to, from,next) {
    //离开时 只需要删除本次编辑所增加的图片
    if(this.perception.body===this.body && this.perception.title===this.title){
      next(true);
    }else{
      if(!this.isEdit && this.body){
        this.$dialog.confirm({
          title: '提示',
          message:'你还没有上传被修改的文章, 离开后将不保存内容，是否确定离开',
        }).then(() => {
          /*不发布 离开页面 判断有没有增加的图片*/
          if(this.newImg.length>0){
            /*如果没有图片就不发送请求*/
            delImgArticle(qs.stringify({imgsrc: JSON.stringify(this.newImg)})).then(respose=>{
              /*删除成功 清空缓存*/
              if(respose.status===200){
                localStorage.removeItem("editaddtupian");
              }
            }).catch(error=>{
              console.log(error);
            })
          }
          next(true);
        }).catch(() => {
          next(false);
        });
      }else{
        next(true);
      }
    }

  },
}
/*修改文章  先增加图片  再删除增加的图片  将丢失路径
目前 ：一开始就存在的图片 最后发布时的图片 只能获取原来的图片有没有删除 无法获取新增图片中有无删除图片
* 保存下新增的图片：每一次新增 压入一个newImg 去跟当前文章中所有图片做一次比较 查看newImg里丢失的图片 */
</script>

<style scoped>
.perception_edit{
  padding: 10px
}
.el-message-box{
  width: 300px!important;
}
</style>
